﻿#ifndef __SS_ASCII_TRIE_NODE_H__
#define __SS_ASCII_TRIE_NODE_H__
#include <memory.h>

namespace StarSeeker
{
	template<typename N_VALUE, unsigned char N_KEY_NUM>
	class ssAsciiTrieNode
	{
		template<typename T_VALUE, unsigned char T_KEY_NUM> friend class ssAsciiTrieTree;
	public:
		ssAsciiTrieNode()
		{
			m_pParent = 0;
			m_key = 0;
			m_pValue = 0;
			m_pOnwer = 0;
			::memset(m_children, 0, N_KEY_NUM*sizeof(ssAsciiTrieNode*));
			m_count = 0;
		}
		~ssAsciiTrieNode()
		{
			Clear();
		}
		N_VALUE* Data()
		{
			return m_pValue;
		}
		char Key()
		{
			return m_key;
		}
		void SetData(N_VALUE* val)
		{
			if (m_pValue)
			{
				delete m_pValue;
			}
			m_pValue = val;
		}
		ssAsciiTrieNode* Find(char key)
		{
			if (key>=0 && key<N_KEY_NUM)
			{
				return m_children[key];
			}
			return 0;
		}
		bool AddChild(char key, ssAsciiTrieNode* node)
		{
			if (key >= 0 && key < N_KEY_NUM)
			{
				if (m_children[key]==0)
				{
					m_children[key] = node;
					++m_count;
					return true;
				}
			}
			return false;
		}
		bool DelChild(char key)
		{
			if (key >= 0 && key < N_KEY_NUM)
			{
				if (m_children[key])
				{
					m_children[key] = 0;
					--m_count;
					return true;
				}
			}
			return false;
		}
		void Clear()
		{
			if (m_pValue)
			{
				delete m_pValue;
			}
			for (int i = 0; i < N_KEY_NUM; i++)
			{
				if (m_children[i])
				{
					delete m_children[i];
					m_children[i] = 0;
				}
			}
			m_pParent = 0;
			m_pValue = 0;
			m_pOnwer = 0;
			m_count = 0;
		}
		void* Onwer()
		{
			return m_pOnwer;
		}
	private:
		ssAsciiTrieNode*	m_pParent;
		N_VALUE*			m_pValue;
		void*				m_pOnwer;
		ssAsciiTrieNode*	m_children[N_KEY_NUM];
		char				m_key;
		unsigned char		m_count;//子节点个数
	};

}
#endif
